<?php
/**
 * cms 附件管理
 * @since   2019-11-30
 * @author  曾
 */

namespace app\admin\controller;


use app\model\FilesManage;
use app\util\ReturnCode;
use app\util\Tools;
use think\Request;

class FilesManageList extends Base {

    /**
     * 获取内容列表
     * @return array
     * @throws \think\exception\DbException
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    public function index() {
        $limit = $this->request->get('size', config('apiAdmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $iscite = $this->request->get('iscite','');
        $filename = $this->request->get('filename','');
        $obj = new FilesManage();
        if (strlen($iscite)) {
            $obj = $obj->where('iscite', $iscite);
        }
        $obj = $obj->whereLike('filename', "%{$filename}%");
        $listObj = $obj->order('createTime DESC')->paginate($limit, false, ['page' => $start])->toArray();

        return $this->buildSuccess([
            'list'  => $listObj['data'],
            'count' => $listObj['total']
        ], '获取成功');
    }

    /**
     * 删除附件
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    public function del() {
        $id = $this->request->get('id');
        if (!$id) {
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '缺少必要参数');
        }
        // 通过ID查文件路径 判断是否存在 存在则最后删除
        $fileId = FilesManage::get($id);
        $fileUrl = '../public' . $fileId->url;
        $image = file_exists($fileUrl); // 判断是否存在
        if ($image) {
            unlink($fileUrl);
            FilesManage::destroy($id);
            return $this->buildSuccess([]);
        } else {
            FilesManage::destroy($id);
            return $this->buildSuccess([]);
        }

    }
}
